import { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { getMirrorOptions, type MirrorNames } from "@/modules/dev-env/mirror/data.ts";
import type { MirrorWebsiteFile } from "@common/spider-types.ts";
import type { ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import semver from "semver";
import { MirrorQueryCondition } from "@/modules/dev-env/mirror/condition.ts";
import type { DefaultOptionType } from "ant-design-vue/es/vc-select/Select";
import { Spider } from "@/ipc/spider.ts";

class KafkaVersionCondition extends MirrorQueryCondition {
  constructor(readonly mirrorUrl: string) {
    super("版本", "version");
  }

  async getDataSource(): Promise<DefaultOptionType[]> {
    const files = await Spider.getMirrorFiles(this.mirrorUrl);
    return files
      .filter(it => it.type === "dir" && /\d+\.\d+\.\d+/.test(it.name))
      .map(it => ({ value: it.name }))
      .sort((a, b) => semver.compare(b.value, a.value));
  }
}

export class KafkaMirror extends BaseEnvMirror {
  private readonly _versionCondition: KafkaVersionCondition;

  constructor(name: MirrorNames) {
    super(getMirrorOptions(name, name === "apache" ? "/kafka/" : "/apache/kafka/"));
    this._versionCondition = new KafkaVersionCondition(this.url);
  }

  protected getConditions0(): MirrorQueryCondition[] {
    return [this._versionCondition];
  }

  protected getRequestUrl(query?: Record<string, any>): string {
    return `${this.url}${query?.version}/`;
  }

  protected getDownloadList0(files: MirrorWebsiteFile[]): ToolInstallVersionItem[] | Promise<ToolInstallVersionItem[]> {
    const versionList: ToolInstallVersionItem[] = [];
    for (const it of files) {
      if (!it.name.startsWith("kafka") || !it.name.endsWith(".tgz") || it.name.includes("src") || it.name.includes("site-doc")) {
        continue;
      }

      // https://mirrors.aliyun.com/apache/kafka/4.0.0/kafka_2.13-4.0.0.tgz
      const downloadUrl = `${this.url}${this._versionCondition.value}/${it.name}`;
      versionList.push({
        id: `kafka-${it.name}`,
        name: path.basename(downloadUrl),
        version: it.name,
        url: downloadUrl,
        date: it.date,
        size: it.size,
      });
    }

    // versionList.sort((a, b) => semver.compare(b.version, a.version));
    return versionList;
  }
}
